﻿using MultiLang;
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;

using Rsdn.Janus.Mssql;

namespace Rsdn.Janus
{
	internal static class SqlSchemaFactory
	{
		public static DataTable GetSchema(SqlConnection con, string collectionName, object[] restrictions)
		{
			var filter = String.Format("CollectionName = '{0}'", collectionName); //MLHIDE

			var ds = new DataSet();
			ds.ReadXml(new StringReader(Resources.MetaData));

			var collection = ds.Tables[DbMetaDataCollectionNames.MetaDataCollections].Select(filter);

			if (collection.Length != 1)
				throw new NotSupportedException(ml.ml_string(20, "Неверное имя коллекции ."));

			if (restrictions != null && restrictions.Length > (int)collection[0]["NumberOfRestrictions"]) //MLHIDE
				throw new InvalidOperationException(ml.ml_string(21, "Количество указанных ограничений неправильное."));

			if (ds.Tables[DbMetaDataCollectionNames.Restrictions].Select(filter).Length !=
				(int)collection[0]["NumberOfRestrictions"])                       //MLHIDE
				throw new InvalidOperationException(ml.ml_string(22, "Указано неправильные количество ограничений."));

			SqlDbSchema returnSchema;
			switch (collectionName.ToLower(CultureInfo.CurrentCulture))
			{
				case "checkconstraints":                                          //MLHIDE
					returnSchema = new SqlCheckConstraints();
					break;
				case "columns":                                                   //MLHIDE
					returnSchema = new SqlColumns();
					break;
				case "defaultconstraints":                                        //MLHIDE
					returnSchema = new SqlDefaultConstraints();
					break;
				case "foreignkeys":                                               //MLHIDE
					returnSchema = new SqlForeignKeys();
					break;
				case "indexes":                                                   //MLHIDE
					returnSchema = new SqlIndexes();
					break;
				case "primarykeys":                                               //MLHIDE
					returnSchema = new SqlPrimaryKeys();
					break;
				case "tables":                                                    //MLHIDE
					returnSchema = new SqlTables();
					break;
				case "triggers":                                                  //MLHIDE
					returnSchema = new SqlTriggers();
					break;
				case "uniquekeys":                                                //MLHIDE
					returnSchema = new SqlUniqueKeys();
					break;
				default:
					throw new NotSupportedException(ml.ml_string(23, "Указанная коллекция метаданных не поддерживается."));
			}

			return returnSchema.GetSchema(con, collectionName, restrictions);
		}
	}
}